package com.traffic.collect.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.traffic.collect.common.agent.AgentProperties;
import com.traffic.collect.entity.TraCollection;
import com.traffic.collect.mapper.TraCollectionMapper;
import com.traffic.collect.service.ICollectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class CollectServiceImpl extends ServiceImpl<TraCollectionMapper, TraCollection> implements ICollectService {
    @Autowired
    AgentProperties agent;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RestTemplate restTemplate;

    @Override
    public void doCollect() {

    }

    @Override
    public void doCollect(TraCollection collection) {
        collection.setInsertTime(LocalDateTime.now());
        this.save(collection);
        collection.setName(agent.getThisName());
        String url=new StringBuffer("http://").append(agent.getIp()).append(":").append(agent.getPort()).append("/").append(agent.getProjectName())
                .append(agent.getInsertData()).toString();

        String key= (String) redisTemplate.opsForValue().get("agent_key");
        if (ObjectUtil.isEmpty(key))
        {
            key=getKey();
            if (ObjectUtil.isNotEmpty(key))
            {
                redisTemplate.opsForValue().set("agent_key",key,10, TimeUnit.MINUTES);
            }
            else {
                throw new RuntimeException("获取token异常");
            }
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        if (ObjectUtil.isNotEmpty(key)) {
            headers.add("X-Access-Token", key);
        }
        extracted(JSON.toJSONString(collection), headers, url);
    }

    private void extracted(String collection, HttpHeaders headers, String url) {
        HttpEntity request1 = new HttpEntity<>(collection, headers);
//        log.info("请求url:{},请求头:{},请求报文：{}", url, JSON.toJSONString(headers), JSON.toJSONString(request1));

        ResponseEntity<String> jsonObjectResponseEntity = null;
        try {
            jsonObjectResponseEntity = restTemplate.postForEntity(url, request1, String.class);
        } catch (RestClientException e) {
            throw new RuntimeException(e);
        }
        log.info("调用代理返回结果{}",jsonObjectResponseEntity);
    }

    private String getKey(){
        String ip=agent.getIp();
        String port=agent.getPort();
        String logUrl=agent.getLoginUrl();
        String url=new StringBuffer("http://").append(ip).append(":").append(port).append("/").append(agent.getProjectName())
                .append(logUrl).toString();

        Map<String, String> map = new HashMap<>();
        map.put("username", agent.getUserName());
        map.put("password", agent.getPassword());

        //处理接收接口只支持JSONOBject
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
//        if (ObjectUtil.isNotEmpty(token)) {
//            headers.add(trafficConfig.getTokenKey(), token);
//        }
        HttpEntity request1 = new HttpEntity<>(JSON.toJSONString(map), headers);
        log.info("请求url:{},请求头:{},请求报文：{}", url, JSON.toJSONString(headers), JSON.toJSONString(request1));

        ResponseEntity<String> jsonObjectResponseEntity = null;
        try {
            jsonObjectResponseEntity = restTemplate.postForEntity(url, request1, String.class);
        } catch (RestClientException e) {
            throw new RuntimeException(e);
        }
        String resp = jsonObjectResponseEntity.getBody();
        log.info("请求返回内容为{}", resp);
        JSONObject jsonObject=JSONObject.parseObject(resp);
        if ("200".equals(String.valueOf(jsonObject.get("code"))))
        {
            JSONObject res=jsonObject.getJSONObject("result");
            return res.getString("token");
        }
        return "";
    }

}
